package com.jww.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/demo06")
public class demo06 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建字节输入流，关联读取的文件
        //获取文件的绝对路径
        String realPath = getServletContext().getRealPath("/img/555.jpg");
        //创建字节输出流的对象
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(realPath));

        //2,设置响应头支持的类型，应用支持的类型为字节流

        resp.setHeader("Content-Type", "application/octet-stream");

        //3,设置响应头以下载的方式打开，以附件形式处理内容

        resp.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + ".jpg");

        //4，获取字节输出流对象
        ServletOutputStream os = resp.getOutputStream();

        //5,读取
        byte[] bytes = new byte[1024];
        int len;
        while ((len = bis.read(bytes)) != -1) {
            os.write(bytes, 0, len);
        }
        bis.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
